<template>
    <div class="goods-container">
        <!-- 顶部搜索和筛选区域 -->
        <div class="search-filter-section">
            <div class="search-wrapper">
                <el-input v-model="searchKeyword" placeholder="搜索商品..." clearable class="search-input"
                    @keyup.enter="handleSearch" @clear="handleSearch">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
                <el-select v-model="categoryFilter" placeholder="分类" clearable @change="handleSearch">
                    <el-option label="全部分类" value=""></el-option>
                    <el-option label="数码产品" value="digital"></el-option>
                    <el-option label="服装鞋帽" value="clothing"></el-option>
                    <el-option label="家居用品" value="home"></el-option>
                    <el-option label="食品饮料" value="food"></el-option>
                </el-select>
                <el-select v-model="sortType" placeholder="排序" @change="handleSearch">
                    <el-option label="默认排序" value="default"></el-option>
                    <el-option label="价格从低到高" value="price_asc"></el-option>
                    <el-option label="价格从高到低" value="price_desc"></el-option>
                    <el-option label="销量从高到低" value="sales_desc"></el-option>
                </el-select>
            </div>
            <div class="view-toggle">
                <el-radio-group v-model="viewMode" size="small">
                    <el-radio-button label="grid">网格</el-radio-button>
                    <el-radio-button label="list">列表</el-radio-button>
                </el-radio-group>
            </div>
        </div>

        <!-- WebSocket消息提示 -->
        <transition name="slide-fade">
            <el-alert v-if="socketMessage" :title="socketMessage" type="success" show-icon :closable="false"
                class="socket-alert">
                <i class="el-icon-bell" slot="title"></i>
            </el-alert>
        </transition>

        <!-- 商品展示区域 -->
        <div class="goods-grid" v-loading="listLoading" :class="{ 'list-view': viewMode === 'list' }">
            <ul class="goods-list">
                <li class="goods-item" v-for="item in GoodsList" :key="item.id" @click="Jump(item.id)">
                    <div class="goods-card">
                        <div class="goods-image-wrapper">
                            <el-image class="goods-image" :src="item.image" :alt="item.goodsName" fit="cover" lazy>
                                <div slot="error" class="image-error">
                                    <i class="el-icon-picture-outline"></i>
                                </div>
                            </el-image>
                            <div class="goods-badges">
                                <span v-if="item.isNew" class="badge new">新品</span>
                                <span v-if="item.isHot" class="badge hot">热销</span>
                                <span v-if="item.discount" class="badge discount">{{ item.discount }}折</span>
                            </div>
                        </div>
                        <div class="goods-info">
                            <h3 class="goods-title" :title="item.goodsName">
                                {{ item.goodsName }}
                            </h3>
                            <div class="goods-price">
                                <div class="current-price">
                                    <span class="price-symbol">¥</span>
                                    <span class="price-integer">{{ Math.floor(item.price) }}</span>
                                    <span class="price-decimal">.{{ (item.price % 1).toFixed(2).slice(2) }}</span>
                                </div>
                                <div v-if="item.originalPrice && item.originalPrice > item.price"
                                    class="original-price">
                                    ¥{{ item.originalPrice.toFixed(2) }}
                                </div>
                            </div>
                            <div class="goods-meta">
                                <div class="sales-info">
                                    <i class="el-icon-s-goods"></i>
                                    已售 {{ item.totalSales || 0 }}
                                </div>
                                <div class="rating" v-if="item.rating">
                                    <el-rate v-model="item.rating" disabled size="small"></el-rate>
                                </div>
                            </div>
                            <div class="goods-actions" v-if="viewMode === 'list'">
                                <el-button size="small" type="primary" @click.stop="addToCart(item)">
                                    <i class="el-icon-shopping-cart-2"></i> 加入购物车
                                </el-button>
                                <el-button size="small" @click.stop="toggleFavorite(item)">
                                    <i :class="item.isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                                </el-button>
                            </div>
                        </div>
                    </div>
                </li>
            </ul>

            <!-- 加载状态 -->
            <div v-if="loading" class="loading-status">
                <i class="el-icon-loading"></i>
                <span>正在加载更多商品...</span>
            </div>

            <!-- 无更多数据提示 -->
            <div v-if="noMoreData && GoodsList.length > 0" class="no-more-data">
                <i class="el-icon-bottom"></i>
                <span>已经到底啦，共 {{ GoodsList.length }} 件商品</span>
            </div>

            <!-- 空状态 -->
            <div v-if="!loading && GoodsList.length === 0" class="empty-state">
                <i class="el-icon-box"></i>
                <h3>暂无商品</h3>
                <p>试试调整筛选条件或搜索其他关键词</p>
            </div>
        </div>

        <!-- 客服聊天窗口 -->
        <div class="customer-service" :class="{ 'expanded': serviceExpanded }">
            <!-- 客服按钮 -->
            <div class="service-trigger" @click="toggleService">
                <div class="service-icon">
                    <i v-if="!serviceExpanded" class="el-icon-service"></i>
                    <i v-else class="el-icon-close"></i>
                </div>
                <el-badge :value="unreadCount" :hidden="!unreadCount || serviceExpanded">
                    <span class="service-text">{{ serviceExpanded ? '关闭' : '客服' }}</span>
                </el-badge>
            </div>

            <!-- 聊天窗口 -->
            <transition name="chat-slide">
                <div v-if="serviceExpanded" class="chat-window">
                    <div class="chat-header">
                        <div class="agent-info">
                            <el-avatar :size="32" src="/customer-service-avatar.jpg">
                                <i class="el-icon-user-solid"></i>
                            </el-avatar>
                            <div class="agent-details">
                                <span class="agent-name">智能客服</span>
                                <span class="agent-status online">
                                    <i class="status-dot"></i>在线
                                </span>
                            </div>
                        </div>
                        <div class="chat-actions">
                            <el-button size="mini" type="text" @click="clearChat">
                                <i class="el-icon-delete"></i>
                            </el-button>
                        </div>
                    </div>

                    <div class="chat-body" ref="chatBody">
                        <div class="message-list">
                            <div v-for="(message, index) in chatMessages" :key="index" class="message-item" :class="{
                                'user-message': message.isUser,
                                'system-message': message.isSystem,
                                'ai-message': !message.isUser && !message.isSystem
                            }">
                                <div class="message-avatar" v-if="message.isUser">
                                    <el-avatar size="small">
                                        <i class="el-icon-user"></i>
                                    </el-avatar>
                                </div>
                                <div class="message-content">
                                    <div class="message-bubble">
                                        {{ message.content }}
                                    </div>
                                    <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                                </div>
                                <div class="message-avatar" v-if="!message.isUser">
                                    <el-avatar size="small" src="/customer-service-avatar.jpg">
                                        <i class="el-icon-user-solid"></i>
                                    </el-avatar>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="chat-footer">
                        <div class="quick-replies" v-if="showQuickReplies">
                            <el-button size="mini" @click="sendQuickReply('商品咨询')">商品咨询</el-button>
                            <el-button size="mini" @click="sendQuickReply('订单查询')">订单查询</el-button>
                            <el-button size="mini" @click="sendQuickReply('售后服务')">售后服务</el-button>
                            <el-button size="mini" @click="sendQuickReply('联系人工')">联系人工</el-button>
                        </div>
                        <div class="input-area">
                            <el-input v-model="messageInput" placeholder="请输入您的问题..." @keyup.enter="sendMessage"
                                :maxlength="200" show-word-limit />
                            <el-button type="primary" @click="sendMessage"
                                :disabled="!messageInput.trim() || isStreaming">
                                {{ isStreaming ? '发送中...' : '发送' }}
                            </el-button>
                        </div>
                    </div>
                </div>
            </transition>
        </div>

        <!-- 回到顶部按钮 -->
        <transition name="fade">
            <div v-if="showBackTop" class="back-to-top" @click="scrollToTop">
                <i class="el-icon-arrow-up"></i>
            </div>
        </transition>
    </div>
</template>

<script>
import { getList } from '@/api/user/goods';
import { ref, onMounted, nextTick } from 'vue';
import { setgoodsId } from '@/api/user/cart';
import { debounce } from 'lodash';
import { getUser } from '@/api/admin/User';
import { getExchange } from '@/api/user/exchange';

export default {
    name: 'EnhancedGoodsInterface',
    data() {
        return {
            // 商品数据
            GoodsList: [],
            currentPage: 1,
            pageSize: 12,
            total: 0,
            listLoading: false,
            loading: false,
            noMoreData: false,
            showBackTop: false,

            // 搜索和筛选
            searchKeyword: '',
            categoryFilter: '',
            sortType: 'default',
            viewMode: 'grid',

            // WebSocket
            socketMessage: '',
            socketTimer: null,
            socket: null,
            userId: '',

            // 客服系统
            serviceExpanded: false,
            unreadCount: 0,
            chatMessages: [
                {
                    content: '您好！欢迎来到我们的商城，我是智能客服小助手。有什么可以帮助您的吗？',
                    isUser: false,
                    isSystem: true,
                    timestamp: new Date()
                }
            ],
            messageInput: '',
            showQuickReplies: true,
            chatId: '',
            isStreaming: false
        };
    },
    methods: {
        // 商品相关方法
        async loadInitialData() {
            this.listLoading = true;
            this.currentPage = 1;
            this.noMoreData = false;

            try {
                const res = await getList(this.currentPage);
                this.GoodsList = res.data.records || res.data.data.records || [];
                this.total = res.data.data?.total || 0;

                this.GoodsList = this.GoodsList.map(item => ({
                    ...item,
                    rating: (Math.random() * 2 + 3).toFixed(1),
                    isNew: Math.random() > 0.8,
                    isHot: Math.random() > 0.7,
                    discount: Math.random() > 0.6 ? Math.floor(Math.random() * 3 + 7) : null,
                    originalPrice: Math.random() > 0.5 ? item.price * (1 + Math.random() * 0.5) : null,
                    isFavorite: false
                }));
            } catch (error) {
                this.$message.error('加载商品失败');
            } finally {
                this.listLoading = false;
            }
        },

        async loadMoreData() {
            if (this.noMoreData || this.loading) return;

            this.loading = true;
            try {
                this.currentPage++;
                const res = await getList(this.currentPage);
                const newData = res.data.data?.records || res.data.data || [];

                if (newData.length === 0) {
                    this.noMoreData = true;
                    return;
                }

                const enhancedData = newData.map(item => ({
                    ...item,
                    rating: (Math.random() * 2 + 3).toFixed(1),
                    isNew: Math.random() > 0.8,
                    isHot: Math.random() > 0.7,
                    discount: Math.random() > 0.6 ? Math.floor(Math.random() * 3 + 7) : null,
                    originalPrice: Math.random() > 0.5 ? item.price * (1 + Math.random() * 0.5) : null,
                    isFavorite: false
                }));

                this.GoodsList = [...this.GoodsList, ...enhancedData];

                if (res.data.total) {
                    this.noMoreData = this.GoodsList.length >= res.data.data.total;
                } else {
                    this.noMoreData = newData.length < this.pageSize;
                }
            } catch (error) {
                this.$message.error('加载更多失败');
                this.currentPage--;
            } finally {
                this.loading = false;
            }
        },

        handleSearch() {
            console.log('搜索:', this.searchKeyword, '分类:', this.categoryFilter, '排序:', this.sortType);
            this.loadInitialData();
        },

        handleScroll: debounce(function () {
            const scrollTop = document.documentElement.scrollTop;
            const scrollBottom = document.documentElement.scrollHeight - window.innerHeight - scrollTop;

            this.showBackTop = scrollTop > 500;
            if (scrollBottom < 200 && !this.noMoreData) {
                this.loadMoreData();
            }
        }, 200),

        scrollToTop() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        },

        Jump(goodsId) {
            this.$router.push({ path: `/ShowGoods/${goodsId}` });
        },

        addToCart(item) {
            setgoodsId({ goodsId: item.id }).then(() => {
                this.$message.success(`${item.goodsName} 已加入购物车`);
            });
        },

        toggleFavorite(item) {
            item.isFavorite = !item.isFavorite;
            this.$message.success(item.isFavorite ? '已添加到收藏' : '已取消收藏');
        },

        // WebSocket相关方法
        showSocketMessage(message) {
            this.socketMessage = message;
            if (this.socketTimer) {
                clearTimeout(this.socketTimer);
            }
            this.socketTimer = setTimeout(() => {
                this.socketMessage = '';
            }, 5000);
        },

        openSocket() {
            if (this.socket) {
                this.socket.close();
                this.socket = null;
            }

            if (typeof WebSocket === 'undefined') {
                this.$message.error('浏览器不支持WebSocket');
                return;
            }

            if (!this.userId) {
                console.warn('用户ID未获取，暂不建立WebSocket连接');
                return;
            }

            const socketUrl = `ws://localhost:8090/imserver/${this.userId}`;
            this.socket = new WebSocket(socketUrl);

            this.socket.onopen = () => {
                console.log('WebSocket连接已建立');
            };

            this.socket.onmessage = (msg) => {
                console.log('收到消息:', msg.data);
                try {
                    const data = JSON.parse(msg.data);
                    this.showSocketMessage(`${data.fromUser}: ${data.content}`);

                    if (data.fromUser !== '系统通知') {
                        this.chatMessages.push({
                            content: data.content,
                            isUser: false,
                            isSystem: false,
                            timestamp: new Date()
                        });
                        this.scrollChatToBottom();

                        if (!this.serviceExpanded) {
                            this.unreadCount++;
                        }
                    }
                } catch (e) {
                    console.error('消息解析失败:', e);
                }
            };

            this.socket.onclose = () => {
                console.log('WebSocket连接已关闭');
                this.socket = null;
            };

            this.socket.onerror = (err) => {
                console.error('WebSocket错误:', err);
            };
        },

        // 客服系统方法
        toggleService() {
            this.serviceExpanded = !this.serviceExpanded;
            if (this.serviceExpanded) {
                this.unreadCount = 0;
                this.scrollChatToBottom();
            }
        },

        // 在Vue组件的sendMessage方法中
        async sendMessage() {
            if (this.isStreaming || !this.messageInput.trim()) return;

            const messageContent = this.messageInput.trim();
            const currentTime = new Date();

            // 添加用户消息
            this.chatMessages.push({
                content: messageContent,
                isUser: true,
                isSystem: false,
                timestamp: currentTime
            });
            this.messageInput = '';
            this.showQuickReplies = false;

            this.isStreaming = true;

            // 创建助手消息占位符
            const assistantMessageIndex = this.chatMessages.length;
            this.chatMessages.push({
                content: '▌', // 打字机光标效果
                isUser: false,
                isSystem: false,
                timestamp: currentTime
            });

            this.scrollChatToBottom();

            try {
                // 使用修复后的API调用
                await getExchange(
                    messageContent,
                    this.chatId,
                    (chunk, fullContent) => {
                        // 实时更新消息内容
                        this.$nextTick(() => {
                            // 清理内容并更新
                            const cleanedContent = fullContent
                                .replace(/<think>.*?<\/think>/gs, '')
                                .replace(/DeepSeek-R1-Lite-Preview/g, '王饲预')
                                .replace(/\s+/g, ' ')
                                .trim();

                            this.chatMessages[assistantMessageIndex].content =
                                cleanedContent || '思考中...';

                            this.scrollChatToBottom();
                        });
                    }
                );

                // 完成后的最终清理
                this.$nextTick(() => {
                    const finalContent = this.chatMessages[assistantMessageIndex].content
                        .replace('▌', '')
                        .trim();

                    if (!finalContent) {
                        this.chatMessages[assistantMessageIndex].content = '抱歉，没有收到回复。';
                    } else {
                        this.chatMessages[assistantMessageIndex].content = finalContent;
                    }
                });

            } catch (error) {
                console.error('发送消息失败:', error);
                this.chatMessages[assistantMessageIndex].content =
                    '对话过程中出现错误，请检查网络后重试。';
            } finally {
                this.isStreaming = false;
                this.scrollChatToBottom();
            }
        },
        sendQuickReply(content) {
            this.messageInput = content;
            this.sendMessage();
        },

        clearChat() {
            this.chatMessages = [
                {
                    content: '您好！欢迎来到我们的商城，我是智能客服小助手。有什么可以帮助您的吗？',
                    isUser: false,
                    isSystem: true,
                    timestamp: new Date()
                }
            ];
            this.showQuickReplies = true;
        },

        scrollChatToBottom() {
            this.$nextTick(() => {
                if (this.$refs.chatBody) {
                    this.$refs.chatBody.scrollTop = this.$refs.chatBody.scrollHeight;
                }
            });
        },

        formatTime(timestamp) {
            return new Date(timestamp).toLocaleTimeString('zh-CN', {
                hour12: false,
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        }
    },

    async mounted() {
        try {
            const userInfo = await getUser();
            this.userId = userInfo?.id || '';
        } catch (error) {
            console.error('获取用户信息失败:', error);
            this.$message.warning('用户信息获取失败，部分功能可能受限');
        }

        this.loadInitialData();
        window.addEventListener('scroll', this.handleScroll);
        this.openSocket();
        this.chatId = Date.now().toString();
    },

    beforeDestroy() {
        window.removeEventListener('scroll', this.handleScroll);
        if (this.socket) {
            this.socket.close();
        }
        if (this.socketTimer) {
            clearTimeout(this.socketTimer);
        }
    }
};
</script>

<style lang="less" scoped>
/* 页面基础容器 */
.goods-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    position: relative;
}

/* 搜索筛选区域 */
.search-filter-section {
    position: sticky;
    top: 0;
    z-index: 100;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    padding: 20px 24px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .search-wrapper {
        display: flex;
        gap: 12px;
        align-items: center;

        .search-input {
            width: 300px;
        }
    }

    .view-toggle {
        .el-radio-group {
            background: #f0f2f5;
            border-radius: 6px;
            padding: 2px;
        }
    }
}

/* 商品展示区域 */
.goods-grid {
    max-width: 1400px;
    margin: 0 auto;
    padding: 24px;

    &.list-view .goods-list {
        grid-template-columns: 1fr;
        gap: 12px;

        .goods-item {
            .goods-card {
                display: flex;
                padding: 16px;

                .goods-image-wrapper {
                    width: 120px;
                    height: 120px;
                    flex-shrink: 0;
                    margin-right: 16px;
                    padding-top: 0;
                }

                .goods-info {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                }
            }
        }
    }
}

.goods-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 24px;
    list-style: none;
    padding: 0;
    margin: 0;
}

.goods-item {
    transition: all 0.3s ease;
    cursor: pointer;

    &:hover {
        transform: translateY(-8px);

        .goods-card {
            box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
        }
    }
}

.goods-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    height: 100%;
}

.goods-image-wrapper {
    position: relative;
    padding-top: 75%;
    background: linear-gradient(45deg, #f8f9fa, #e9ecef);
    overflow: hidden;

    .goods-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        transition: transform 0.3s ease;
    }

    .goods-item:hover & .goods-image {
        transform: scale(1.05);
    }

    .image-error {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #c0c4cc;
        font-size: 24px;
    }

    .goods-badges {
        position: absolute;
        top: 12px;
        left: 12px;
        display: flex;
        flex-direction: column;
        gap: 6px;

        .badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 600;
            color: #fff;

            &.new {
                background: linear-gradient(135deg, #67c23a, #85ce61);
            }

            &.hot {
                background: linear-gradient(135deg, #f56c6c, #f78989);
            }

            &.discount {
                background: linear-gradient(135deg, #e6a23c, #eebe77);
            }
        }
    }
}

.goods-info {
    padding: 20px;
}

.goods-title {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    line-height: 1.4;
    color: #1a1a1a;
    height: 44px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

.goods-price {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;

    .current-price {
        display: flex;
        align-items: baseline;
        color: #e53e3e;

        .price-symbol {
            font-size: 14px;
            margin-right: 2px;
        }

        .price-integer {
            font-size: 24px;
            font-weight: 700;
        }

        .price-decimal {
            font-size: 16px;
            font-weight: 600;
        }
    }

    .original-price {
        color: #999;
        text-decoration: line-through;
        font-size: 14px;
    }
}

.goods-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #666;
    font-size: 14px;

    .sales-info {
        display: flex;
        align-items: center;
        gap: 4px;

        i {
            color: #409eff;
        }
    }
}

.goods-actions {
    display: flex;
    gap: 8px;
    margin-top: 12px;
}

/* 加载 & 空状态 */
.loading-status {
    padding: 40px 0;
    text-align: center;
    color: #666;
    font-size: 16px;

    .el-icon-loading {
        animation: rotating 1.5s linear infinite;
        margin-right: 8px;
        font-size: 20px;
    }
}

.no-more-data {
    padding: 40px 0;
    text-align: center;
    color: #999;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;

    i {
        font-size: 18px;
    }
}

.empty-state {
    padding: 80px 0;
    text-align: center;
    color: #999;

    i {
        font-size: 64px;
        margin-bottom: 16px;
        display: block;
    }

    h3 {
        margin: 0 0 8px 0;
        font-size: 18px;
        color: #666;
    }

    p {
        margin: 0;
        font-size: 14px;
    }
}

/* WebSocket 消息提示 */
.socket-alert {
    position: fixed;
    top: 80px;
    right: 24px;
    width: 320px;
    z-index: 2000;
    border-radius: 12px;
    border-left: 4px solid #67c23a;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
    transition: all 0.3s ease;
}

.slide-fade-enter,
.slide-fade-leave-to {
    transform: translateX(100%);
    opacity: 0;
}

/* 客服系统 */
.customer-service {
    position: fixed;
    bottom: 32px;
    right: 32px;
    z-index: 1100;

    .service-trigger {
        width: 60px;
        height: 60px;
        background: #fff;
        border: 2px solid #409eff;
        border-radius: 50%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;

        &:hover {
            background: #409eff;
            color: #fff;
            box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
            transform: translateY(-2px);
        }

        .service-icon {
            font-size: 24px;
            margin-bottom: 4px;
        }

        .service-text {
            font-size: 12px;
            font-weight: 500;
        }

        .el-badge__content {
            top: 8px;
            right: 8px;
            transform: translate(50%, -50%);
        }
    }

    &.expanded .service-trigger {
        background: #f56c6c;
        border-color: #f56c6c;
        color: #fff;

        &:hover {
            background: #ff7875;
            box-shadow: 0 6px 16px rgba(245, 108, 108, 0.3);
        }
    }

    .chat-window {
        position: absolute;
        bottom: 80px;
        right: 0;
        width: 360px;
        height: 480px;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
        display: flex;
        flex-direction: column;
        overflow: hidden;
        border: 1px solid #e8ecef;
    }

    .chat-header {
        padding: 12px 16px;
        background: #f8f9fa;
        border-bottom: 1px solid #e8ecef;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .agent-info {
            display: flex;
            align-items: center;
            gap: 10px;

            .agent-details {
                display: flex;
                flex-direction: column;

                .agent-name {
                    font-size: 14px;
                    font-weight: 500;
                    color: #333;
                }

                .agent-status {
                    font-size: 12px;
                    color: #67c23a;
                    display: flex;
                    align-items: center;
                    gap: 4px;

                    .status-dot {
                        width: 6px;
                        height: 6px;
                        background: #67c23a;
                        border-radius: 50%;
                    }
                }
            }
        }

        .chat-actions {
            .el-button {
                color: #606266;
                padding: 4px;

                &:hover {
                    color: #409eff;
                    background: #f0f2f5;
                    border-radius: 4px;
                }
            }
        }
    }

    .chat-body {
        flex: 1;
        overflow-y: auto;
        padding: 12px;
        background: #f5f7fa;

        &::-webkit-scrollbar {
            width: 6px;
        }

        &::-webkit-scrollbar-thumb {
            background: #c0c4cc;
            border-radius: 4px;
        }

        .message-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .message-item {
            display: flex;
            align-items: flex-start;
            gap: 8px;
            margin: 4px 0;

            &.user-message {
                justify-content: flex-end;

                .message-content {
                    align-items: flex-end;

                    .message-bubble {
                        background: #e6f7ff;
                        border: 1px solid #b3e5fc;
                        border-radius: 12px 12px 2px 12px;
                        color: #1a1a1a;
                    }
                }
            }

            &.ai-message {
                .message-content {
                    align-items: flex-start;

                    .message-bubble {
                        background: #fff;
                        border: 1px solid #e8ecef;
                        border-radius: 12px 12px 12px 2px;
                        color: #333;
                    }
                }
            }

            &.system-message {
                justify-content: center;
                margin: 8px 0;

                .message-content {
                    align-items: center;

                    .message-bubble {
                        background: #f0f2f5;
                        color: #606266;
                        border-radius: 12px;
                        font-size: 12px;
                        padding: 8px 12px;
                    }

                    .message-time {
                        display: none;
                    }
                }

                .message-avatar {
                    display: none;
                }
            }

            .message-avatar {
                flex-shrink: 0;
            }

            .message-content {
                display: flex;
                flex-direction: column;
                max-width: 75%;

                .message-bubble {
                    padding: 10px 14px;
                    font-size: 14px;
                    line-height: 1.5;
                    word-wrap: break-word;
                    transition: all 0.2s ease;
                }

                .message-time {
                    font-size: 10px;
                    color: #909399;
                    margin-top: 4px;
                    padding: 0 4px;
                }
            }
        }
    }

    .chat-footer {
        background: #fff;
        border-top: 1px solid #e8ecef;
        padding: 12px;

        .quick-replies {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
            margin-bottom: 8px;

            .el-button {
                font-size: 12px;
                padding: 6px 12px;
                border-radius: 16px;
                background: #f0f2f5;
                border: none;
                color: #606266;

                &:hover {
                    background: #409eff;
                    color: #fff;
                }
            }
        }

        .input-area {
            display: flex;
            gap: 8px;
            align-items: center;

            .el-input {
                flex: 1;

                /deep/ .el-input__inner {
                    border-radius: 16px;
                    border: 1px solid #d9dee4;
                    padding: 8px 12px;
                    font-size: 14px;
                }
            }

            .el-button {
                border-radius: 16px;
                padding: 8px 16px;
                font-size: 14px;
                background: #409eff;
                border: none;

                &:hover {
                    background: #66b1ff;
                }

                &:disabled {
                    background: #c0c4cc;
                    cursor: not-allowed;
                }
            }
        }
    }
}

.chat-slide-enter-active,
.chat-slide-leave-active {
    transition: all 0.3s ease;
}

.chat-slide-enter {
    opacity: 0;
    transform: translateY(20px);
}

.chat-slide-leave-to {
    opacity: 0;
    transform: translateY(-20px);
}

/* 回到顶部按钮 */
.back-to-top {
    position: fixed;
    bottom: 120px;
    right: 24px;
    width: 50px;
    height: 50px;
    background: rgba(64, 158, 255, 0.9);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #fff;
    font-size: 20px;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);

    &:hover {
        background: #409eff;
        transform: translateY(-2px);
    }
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s;
}

.fade-enter,
.fade-leave-to {
    opacity: 0;
}

/* 动画定义 */
@keyframes rotating {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

@keyframes pulse {

    0%,
    100% {
        opacity: 1;
        transform: scale(1);
    }

    50% {
        opacity: 0.7;
        transform: scale(1.1);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .search-filter-section {
        flex-direction: column;
        gap: 16px;
        padding: 16px;

        .search-wrapper {
            flex-direction: column;
            width: 100%;

            .search-input,
            .el-select {
                width: 100%;
            }
        }
    }

    .goods-list {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
        padding: 0 12px;
    }

    .goods-title {
        font-size: 14px;
        height: 40px;
    }

    .socket-alert {
        width: calc(100% - 32px);
        right: 16px;
        left: 16px;
    }

    .customer-service {
        bottom: 16px;
        right: 16px;

        .chat-window {
            width: calc(100vw - 32px);
            height: 60vh;
            bottom: 70px;
            left: 16px;
            right: 16px;
        }

        .service-trigger {
            width: 56px;
            height: 56px;

            .service-icon {
                font-size: 22px;
            }

            .service-text {
                font-size: 11px;
            }
        }
    }
}

@media (max-width: 480px) {
    .goods-list {
        grid-template-columns: 1fr;
    }

    .customer-service {
        .chat-window {
            width: calc(100vw - 24px);
            height: 50vh;
            left: 12px;
            right: 12px;
        }

        .service-trigger {
            width: 50px;
            height: 50px;

            .service-icon {
                font-size: 20px;
            }

            .service-text {
                font-size: 10px;
            }
        }
    }
}
</style>